package com.tz.platform.dao;

import com.tz.platform.page.PageCondition;
import com.tz.platform.utils.StringUtil;

public class DaoUtils<T> {

	/**
	 * 拼接SQL 进行查询
	 * @param hql
	 * @return
	 */
	public String formatHql(String hql,PageCondition condition){
		String sql = "";
		String queryString=condition.getQueryString();
		if(!StringUtil.msIsEmpty(queryString)){
			//拼接where查询条件
			if(hql.contains("where")){
				sql = hql + " and " + queryString;
			}else{
				sql = hql + " where " + queryString;
			}
		}else{
			sql = hql;
		}
		//拼接order by排序条件
		String sortByString=condition.getSortBys();
		if(!StringUtil.msIsEmpty(sortByString)){
			sql += " "+sortByString;
		}
		return sql;
	}
	
	/**
	 * 重新组装sql,生成查询总条数的sql
	 * @param sql
	 * @return
	 */
	public String formatCountSql(String sql){
		int selectIndex=sql.indexOf("select");
		int fromIndex=sql.indexOf("from");
		String result=null;
		if(selectIndex!=-1){
			if(fromIndex!=-1){
				result="select count(1) "+sql.substring(fromIndex);
			}
		}else if(fromIndex!=-1){
			result="select count(1) "+sql;
		}
		return result;
	}
	

}